package br.com.mensageiro.negocio.servico.impl;

import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import br.com.mensageiro.negocio.entidade.Empresa;
import br.com.mensageiro.negocio.entidade.Usuario;
import br.com.mensageiro.negocio.servico.IAuthenticationService;
import br.com.mensageiro.negocio.servico.IUsuarioService;

@Service("authenticationService")
public class AuthenticationService implements IAuthenticationService, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Resource(name = "authenticationManager")
	private AuthenticationManager authenticationManager;
	@Autowired
	private IUsuarioService usuarioService;

	@PostConstruct
	public void init() {
		System.out.println("Service iniciado " + this.getClass().getName());
	}

	@Override
	public boolean login(String username, String password, Empresa empresa) {
		try {
			username += "." + empresa.getId();
			Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
			if (authenticate.isAuthenticated()) {
				SecurityContextHolder.getContext().setAuthentication(authenticate);
				return true;
			}

		} catch (AuthenticationException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean autenticar(String username, String password) {
		Usuario usuario = usuarioService.getUsuarioByLogin(username);
		if (usuario != null) {
			if (usuario.getSenhaHash().equals(PasswordSupport.getMD5Hash(password))) {
				return true;
			}
		}

		return false;
	}
}
